using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using 第五课.Models.Database;

namespace 第五课
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            //新增该行代码，为程序注入MVC服务
            services.AddControllersWithViews();

            //使用数据库 依赖注入 在Startup文件的ConfigureServices注入DbContext
            services.AddDbContext<Store_2022Context>();

            //添加授权规则为cookie 当未登录时跳转到Login.html
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(
                options => { options.LoginPath = new PathString("/Login.html"); } //设置登录页面为/Auth/Signin
            );
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //使用静态文件()
            app.UseStaticFiles();

            app.UseRouting();

            //启用身份验证，加上这句才能生效，
            //注意顺序，在 app.UseRouting();之后
            //开启认证中间件
            app.UseAuthentication();
            //开启授权中间件
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                //endpoints.MapGet("/", async context =>
                //{
                //    await context.Response.WriteAsync("Hello World!");
                //});
                //把原来这行代码修改为以下代码
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
